package com.superhelper.receiver.web.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.common.domain.baidu.BdPushEntity;
import com.superhelper.common.service.AliMQProducerService;
import com.superhelper.common.utils.JsonHelper;
import com.superhelper.receiver.service.BdPushValidService;

/**
 * 百度消息推送
 */
@Controller
@RequestMapping("/push/bd")
public class BdReceiverController {
    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AliMQProducerService producer;

    @Autowired
    private BdPushValidService validService;

    @RequestMapping("/ping")
    @ResponseBody
    public String ping() {
        return "{\"data\":\"OK\"}";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/order")
    @ResponseBody
    public Map<String, Object> order(String cmd, String ticket, String sign, String source, String body, String version,
            Long timestamp, String encrypt, HttpServletRequest request) {
        // showParams(request);
        BdPushEntity entity = new BdPushEntity();
        entity.setBody(JsonHelper.fromJson(body, Map.class));
        entity.setCmd(cmd);
        entity.setEncrypt(encrypt);
        entity.setSign(sign);
        entity.setSource(source);
        entity.setTicket(ticket);
        entity.setTimestamp(timestamp);
        entity.setVersion(version);
        return doService(entity);
    }

    private void showParams(HttpServletRequest request) {
        Map map = new HashMap();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();

            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }

        Set<Map.Entry<String, String>> set = map.entrySet();
        log.info("------------------------------");
        for (Map.Entry entry : set) {
            log.info(entry.getKey() + ":" + entry.getValue());
        }
        log.info("------------------------------");
    }

    private Map<String, Object> doService(BdPushEntity entity) {
        boolean sendResult = false;
        try {
            sendResult = producer.sendBdOrder(entity);
        } catch (Exception e) {
            log.error("doService error", e);
        }

        Map<String, Object> result = new TreeMap<>();
        result.put("cmd", entity.getCmd());
        result.put("source", entity.getSource());
        result.put("ticket", entity.getTicket());
        result.put("timestamp", System.currentTimeMillis() / 1000);
        result.put("version", "3");
        result.put("encrypt", entity.getEncrypt());

        Map<String, Object> body = new HashMap<>();
        result.put("body", body);
        body.put("errno", sendResult ? 0 : 1);
        body.put("error", sendResult ? "success" : "fail");

        if (sendResult) {
            Map<String, Object> data = new HashMap<>();
            body.put("data", data);
            data.put("source_order_id", entity.getBody().get("order_id"));
        }
        result.put("sign", validService.getSign(result));
        // {
        // "body": {
        // "errno": 0,
        // "error": "success",
        // "data":{
        // "source_order_id":"123456789***"
        // }
        // },
        // "cmd": "resp.order.create",
        // "sign": "51BAA29E9CE298241F52985864D23165",
        // "source": "65400",
        // "ticket": "FEBCA99A-967D-EBDC-8588-F530B3E235E7",
        // "timestamp": 1452686921,
        // "version": 3
        // }

        return result;
    }

    public static void main(String[] args) {

        Map<String, Object> result = new TreeMap<>();
        result.put("cmd", "order.create");
        result.put("source", "64773");
        result.put("ticket", "1");
        result.put("timestamp", 1499176565);
        result.put("version", 3);

        Map<String, Object> body = new HashMap<>();
        result.put("body", body);
        body.put("errno", 1);
        body.put("error", "fail");

        System.out.println(JsonHelper.toJson(result));

    }
}
